using System;
using System.Configuration;
using System.Collections;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

namespace PlacementManager
{
    /// <summary>
    /// Summary description for GoogleMap
    /// </summary>
    public class GoogleMap
    {
        public GoogleMap()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public float[] GetLongitudeLatitude(string address)
        {
            string url = "http://maps.google.com/maps?q=";
            url += address;
            url += "&output=kml";
            url += "&key=" + System.Configuration.ConfigurationManager.AppSettings["GOOGLEMAPS_KEY"].ToString();
            
            WebRequest webRequest = WebRequest.Create(url);

            bool useProxy = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["USEPROXY"].ToString());
            if (useProxy)
            {
                WebProxy webProxy = new WebProxy(System.Configuration.ConfigurationManager.AppSettings["PROXYNAME"].ToString(), Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["PROXYPORT"].ToString()));
                webRequest.Proxy = webProxy;
            }

            float[] coordinates = new float[2];
            try
            {
                WebResponse webResponse = webRequest.GetResponse();
                //Added By hitesh as some of the addresses which are not input properly in
                // the import excel file slows down the script and eventually script manager times out
                if (webResponse.ContentLength == -1)
                    return coordinates;
                StreamReader reader = new StreamReader(webResponse.GetResponseStream());
                string str = reader.ReadToEnd();
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(str);

                XmlNodeList nodelistLong = xmlDocument.GetElementsByTagName("longitude");
                XmlNodeList nodelistLat = xmlDocument.GetElementsByTagName("latitude");


                coordinates[0] = float.Parse(nodelistLong[0].InnerText);
                coordinates[1] = float.Parse(nodelistLat[0].InnerText);

                return coordinates;
            }
            catch (Exception ex)
            {
                coordinates[0] = 0;
                coordinates[1] = 0;

                return coordinates;
            }
        }
    } 
}
